#include "paramdelete.h"
#include "ui_paramdelete.h"
#include "msgbox.h"
#include "userlogger.h"

ParamDelete::ParamDelete(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ParamDelete)
{
    ui->setupUi(this);
    bdf = BllDataFlow::getInstance();
    sqlHelper = SqlHelper::getInstance();

    //Signals and Slots
    connect(bdf, &BllDataFlow::sendDeleteParameterSignal, this, &ParamDelete::setParameter);
    connect(bdf, &BllDataFlow::retranslateUiSignal, this, &ParamDelete::retranslateUiSlot);

    setAttribute(Qt::WA_TranslucentBackground, true);
    QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect();
    shadow->setColor(QColor(0,0,0,150));
    shadow->setOffset(1, 1);
    shadow->setBlurRadius(16);
    ui->widget->setGraphicsEffect(shadow);
}

ParamDelete::~ParamDelete()
{
    delete ui;
}

void ParamDelete::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.fillRect(this->rect(), QColor(255, 255, 255, 0));
}

void ParamDelete::on_btnClose_clicked()
{
    this->hide();
}

void ParamDelete::retranslateUiSlot()
{
    ui->retranslateUi(this);
}

void ParamDelete::setParameter(const Parameter &parameter)
{
    param = parameter;
    ui->lblMsg->setText(QString(tr("Would you like to delete %1 ?")).arg(param.name));
    bool isOn = sqlHelper->checkParamIson(param.name);
    if(isOn)
    {
        MsgBox::information(this,
                                 QString(tr("Parameter")),
                                 QString(tr("Parameter is on!")));
        this->hide();
    }
    else
    {
        this->show();
    }
}

void ParamDelete::on_btnConfirm_clicked()
{
    UserLogger::log(QString("%1: %2(%3)\n>%4: %5V, %6: %7μs, %8: %9ml/min, %10: %11ms, %12: %13")
                    .arg(tr("Delete parameters")).arg(param.name).arg(param.code)
                    .arg(tr("Voltage")).arg(param.volt)
                    .arg(tr("Pulse")).arg(param.pulse)
                    .arg(tr("Flow Rate")).arg(param.speed)
                    .arg(tr("Interval")).arg(param.interval)
                    .arg(tr("Times")).arg(param.times));

    EttaError ret = sqlHelper->deleteParameterItem(param.name);
    if (EttaError::OK == ret)
    {
        QString message = tr("Success to delete parameter");
        UserLogger::log(QString("%1: %2(%3)").arg(message).arg(param.name).arg(param.code));
        bdf->showAllParameters();
        this->hide();
    }
    else
    {
        QString message = tr("Fail to delete parameter");
        UserLogger::log(QString("%1: %2(%3)").arg(message).arg(param.name).arg(param.code));
        this->hide();
        MsgBox::information(this, tr("Parameter"), message);
    }
}

void ParamDelete::on_btnCancel_clicked()
{
    this->hide();
}
